package com.knowledge.knowledge_notes.controller;

import com.knowledge.knowledge_notes.annotation.ApiRestController;
import com.knowledge.knowledge_notes.common.ResultVo;
import com.knowledge.knowledge_notes.dao.AdminRoleDAO;
import com.knowledge.knowledge_notes.dao.AdminRolePermissionDAO;
import com.knowledge.knowledge_notes.pojo.AdminPermission;
import com.knowledge.knowledge_notes.pojo.AdminRole;
import com.knowledge.knowledge_notes.service.AdminPermissionService;
import com.knowledge.knowledge_notes.service.AdminRoleMenuService;
import com.knowledge.knowledge_notes.service.AdminRolePermissionService;
import com.knowledge.knowledge_notes.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@ApiRestController
public class RoleController {

    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    AdminPermissionService adminPermissionService;
    @Autowired
    AdminRolePermissionService adminRolePermissionService;
    @Autowired
    AdminRoleMenuService adminRoleMenuService;

    @GetMapping("/admin/role")
    public ResultVo listRoles() {
        return ResultVo.OK(adminRoleService.listWithPermsAndMenus());
    }

    @PostMapping("/admin/role")
    public ResultVo addRole(@RequestBody AdminRole requestRole) {
        adminRoleService.editRole(requestRole);
        return ResultVo.OK("新增用户成功");
    }

    @PutMapping("/admin/role")
    public ResultVo editRole(@RequestBody AdminRole requestRole) {
        try {
            adminRoleService.addOrUpdate(requestRole);
            adminRolePermissionService.savePermChanges(requestRole.getId(), requestRole.getPerms());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.FAIL("修改角色信息异常");
        }
        return ResultVo.OK("修改角色信息成功");
    }

    @DeleteMapping("/admin/role")
    public ResultVo deleteRole(@RequestParam int id) {
        try {
            AdminRole requestRole = new AdminRole();
            requestRole.setId(id);
            adminRoleService.deleteRole(requestRole);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.FAIL("删除角色信息异常");
        }
        return ResultVo.OK("删除角色信息成功");
    }

    @GetMapping("/admin/role/perm")
    public ResultVo listPerms() {
        return ResultVo.OK(adminPermissionService.list());
    }

    @PutMapping("/admin/role/menu")
    public ResultVo updateRoleMenu(@RequestParam int rid, @RequestBody Map<String, List<Integer>> menusIds) {
        adminRoleMenuService.updateRoleMenu(rid, menusIds);
        return ResultVo.OK("更新成功");
    }
}
